package com.wang.example.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.SocketException;

public class BioClient {
    public static void main(String[] args) throws IOException, InterruptedException {
        //通过构造函数创建Socket，并且连接指定地址和端口的服务端
        Socket socket = new Socket("127.0.0.1", 9000);
        //启动读取服务端数据的线程
        new ReadMsg(socket).start();
        while (true) {
            socket.getOutputStream().write("你好".getBytes());
            Thread.sleep(3000);
        }
    }
    //读取服务端输出数据的线程
    private static class ReadMsg extends Thread {
        Socket socket;
        public ReadMsg(Socket socket) {
            this.socket = socket;
        }
        @Override
        public void run() {
            //接收来自服务端的消息
            try (
                    InputStream is = socket.getInputStream()
            ) {
                byte[] b = new byte[1024];
                while (true) {//循环读取数据
                    //阻塞方法，只有等到数据准备好，才会往下执行
                    int data = is.read(b);
                    if (data != -1) {
                        String info = new String(b, 0, data, "UTF-8");
                        System.out.println("收到来自服务端的消息：" + info);
                    } else {
                        break;
                    }
                }
            } catch (SocketException e) {
                System.out.printf("%s\n", "服务器断开了你的连接");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (socket != null){
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
